package cn.ghjcloud.marking.commons.handler;

import cn.ghjcloud.marking.commons.exception.MyException;
import cn.ghjcloud.marking.commons.model.Result;
import cn.ghjcloud.marking.commons.model.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义的公共异常处理器
 *      1.声明异常处理器
 *      2.对异常统一处理
 */
@ControllerAdvice
public class MyExceptionHandler {
	private static final Logger LOGGER=LoggerFactory.getLogger(ExceptionHandler.class);

	//捕获MyException此类异常
	@ExceptionHandler(MyException.class)
	@ResponseBody
	public Result myException(MyException myException) {
		//输出日志
		LOGGER.error("捕获一个异常：{}", myException.getMessage());
		ResultCode resultCode=myException.getResultCode();
		return new Result(resultCode);
	}

	//捕获Exception此类异常
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public Result Exception(Exception exception) {
		//输出日志
		LOGGER.error("捕获一个异常：{}", exception.getMessage());
		ResultCode resultCode=exceptionMap.get(exception.getClass());
		if (resultCode != null) {
			return new Result(resultCode);
		}
		return new Result(ResultCode.SERVER_ERROR);
	}

	static Map<Class<? extends Throwable>, ResultCode> exceptionMap=new HashMap<>();

	//在这里加入其他异常类型判断
	static {
		/*exceptionMap.put(AuthenticationException.class, ResultCode.UNAUTHENTICATED);
		exceptionMap.put(UnauthorizedException.class, ResultCode.UNAUTHORISE);
		exceptionMap.put(HttpRequestMethodNotSupportedException.class, ResultCode.REQUEST_METHOD_ERROR);*/
	}
}